package com.jqr.activity.handlerlistviewsqlitedemo;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.jqr.activity.handlerlistviewsqlitedemo.helper.DatabaseHelper;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    ListView userListView;

    private ArrayAdapter<String> adapter;


    private List<String> userData;

    private Handler handler;

    private DatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userListView=findViewById(R.id.userListView);

        userData=new ArrayList<>();

        adapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,userData);

        userListView.setAdapter(adapter);

        dbHelper=new DatabaseHelper(this);

        handler=new Handler(Looper.getMainLooper());

        new Thread(new Runnable() {
            @Override
            public void run() {
                dbHelper.insertUser("rose",23);
                dbHelper.insertUser("Jordan",62);
                dbHelper.insertUser("张三",32);
                dbHelper.insertUser("李四",43);
                dbHelper.insertUser("黄老邪",55);

                Cursor cursor=dbHelper.getAllUsers();

                // 准备要显示的数据
                final List<String> users = new ArrayList<>();
                if (cursor != null && cursor.moveToFirst()) {
                    do {
                        String name = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_NAME));
                        int age = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseHelper.COLUMN_AGE));
                        users.add("Name: " + name + ", Age: " + age);
                    } while (cursor.moveToNext());
                    cursor.close();
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        userData.clear();
                        userData.addAll(users);
                        adapter.notifyDataSetChanged();

                    }
                });



            }
        }).start();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        handler.removeCallbacksAndMessages(null); //防止Handler 内存泄漏
    }
}